package org.keyroy.mapEditor.ui.views;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.keyroy.map.core.manages.Resource;
import org.keyroy.map.core.manages.ResourceManage;
import org.keyroy.map.core.sprite.Sprite;
import org.keyroy.map.render.SWTResourceLoader;

public class SpriteView extends Composite {
	private Sprite[][] sprites;
	private Resource resource;
	private Rectangle rectangle = new Rectangle(0, 0, 0, 0);
	/**
	 * @wbp.parser.constructor
	 */
	public SpriteView(Composite parent) {
		this(parent, true);
	}

	public SpriteView(Composite parent, final boolean isCenter) {
		super(parent, SWT.DOUBLE_BUFFERED);
		addPaintListener(new PaintListener() {

			@Override
			public void paintControl(PaintEvent e) {
				if (sprites != null) {
					GC graphics2d = e.gc;

					int px = (e.width - rectangle.width) / 2;
					int py = (e.height - rectangle.height) / 2;

					if (isCenter == false) {
						px = 0;
						py = 0;
					}

					for (int x = 0; x < sprites.length; x++) {
						for (int y = 0; y < sprites[x].length; y++) {
							Sprite sprite = sprites[x][y];
							if (sprite != null) {
								int tx = px + resource.pw * x;
								int ty = py + resource.ph * y;

								{ // swt
									Image image = SWTResourceLoader.getSWTImage(sprite);
									if (image == null) {
										(graphics2d).fillRectangle(tx, ty, resource.pw, resource.ph);
									} else {
										(graphics2d).drawImage(image, tx, ty);
									}
								}
							}
						}
					}

					rectangle.x = px;
					rectangle.y = py;
					graphics2d.drawRectangle(rectangle);
				}
			}
		});
	}

	public Sprite[][] getSprites() {
		return sprites;
	}

	public void set(Resource resource, Sprite[][] sprites) {
		this.sprites = sprites;
		this.resource = resource;
		if (this.sprites != null) {
			if (this.resource == null) {
				for (int x = 0; x < sprites.length; x++) {
					for (int y = 0; y < sprites[x].length; y++) {
						if (sprites[x][y] != null) {
							this.resource = ResourceManage.getResource(sprites[x][y].getResourceID());
							break;
						}
					}
				}
			}
			rectangle.width = sprites.length * this.resource.pw;
			rectangle.height = sprites[0].length * this.resource.ph;
		}
		redraw();
	}

	public void autosize() {
		setSize(rectangle.width + 1, rectangle.height + 1);
	}

	public void set(Sprite sprite) {
		Sprite[][] sprites = new Sprite[1][1];
		sprites[0][0] = sprite;
		set(null, sprites);
	}

	@Override
	protected void checkSubclass() {
	}

}
